package tencentcloud

import (
	"context"
	"encoding/base64"
	"github.com/spf13/viper"
	"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common"
	"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common/profile"
	ocr "github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/ocr/v20181119"
	"go.uber.org/zap"
	"golang-sgg-daijia/pkg/log"
)

type OcrClient interface {
	IDCardOCR(ctx context.Context, image []byte) (*ocr.IDCardOCRResponse, error)
	DriverLicense(ctx context.Context, image []byte) (*ocr.DriverLicenseOCRResponse, error)
}

type ocrClient struct {
	ocrCli *ocr.Client
	logger *log.Logger
}

func NewOcrClient(
	ocrCli *ocr.Client,
	logger *log.Logger,
) OcrClient {
	return &ocrClient{
		ocrCli: ocrCli,
		logger: logger,
	}
}

func NewOcrCli(conf *viper.Viper) *ocr.Client {
	credential := common.NewCredential(
		conf.GetString("security.tencentclould.secret_Id"),
		conf.GetString("security.tencentclould.secret_key"),
	)
	cpf := profile.NewClientProfile()
	cpf.HttpProfile.Endpoint = "ocr.tencentcloudapi.com"

	client, err := ocr.NewClient(credential, "", cpf)
	if err != nil {
		panic(err)
	}
	return client
}

func (cli *ocrClient) IDCardOCR(ctx context.Context, image []byte) (*ocr.IDCardOCRResponse, error) {
	request := ocr.NewIDCardOCRRequest()
	dst := make([]byte, base64.StdEncoding.EncodedLen(len(image)))
	base64.StdEncoding.Encode(dst, image)
	request.ImageBase64 = common.StringPtr(string(dst))
	response, err := cli.ocrCli.IDCardOCRWithContext(ctx, request)
	if err != nil {
		cli.logger.WithContext(ctx).Error("ocrClient|IdCardOCR|IDCardOCRWithContext", zap.Error(err))
		return nil, err
	}
	return response, nil
}

func (cli *ocrClient) DriverLicense(ctx context.Context, image []byte) (*ocr.DriverLicenseOCRResponse, error) {
	request := ocr.NewDriverLicenseOCRRequest()
	dst := make([]byte, base64.StdEncoding.EncodedLen(len(image)))
	base64.StdEncoding.Encode(dst, image)
	request.ImageBase64 = common.StringPtr(string(dst))
	response, err := cli.ocrCli.DriverLicenseOCRWithContext(ctx, request)
	if err != nil {
		cli.logger.WithContext(ctx).Error("ocrClient|IdCardOCR|DriverLicenseOCRWithContext", zap.Error(err))
		return nil, err
	}
	return response, nil
}
